<template>
  <div class='phoneInfo'>
    <div style="position:relative">
      <div style="position:absolute;left:50%;bottom:50%;transform:translate(-50%);font-size:16px;color:#fff;">验证手机号</div>
      <img width='100%' src="~@/assets/images/myInfo/info_top.png" alt="">
    </div>
    <div class="midContent">
      <div style="margin-bottom:20px;text-align:left;">
        <img style="position:relative;top:5px;width:25px;height:25px;margin-right:10px" src="~@/assets/images/myInfo/info_phone.png" alt=""> <span style="font-size:16px;line-height:30px">请填写手机号及验证码</span>
      </div>
      <div style="margin-bottom:20px;color: #8A8982;font-size:14px;text-align:left;">我们将在系统中匹配您的保单信息以便查看</div>
      <div style="width:100%;text-align:left">
        <div style="margin:20px 0;height:26px;">
          <span style="color:red;width:10%">*</span>
          <span style="color: #8A8982;font-size:14px;width:20%;margin:0 20px 0 15px">手机号</span>
          <input style="width:60%;font-size:14px;" placeholder="请输入手机号" v-model="phoneNumber" type="text">
        </div>
        <div style="margin:25px 0;height:26px;">
          <span style="color:red;width:10%">*</span>
          <span style="color: #8A8982;font-size:14px;width:20%;margin:0 20px 0 15px">验证码</span>
          <input style="width:40%;font-size:14px;" type="text" placeholder="请输入验证码" v-model="checkCode" >
          <div style="text-align:center;color: #8A8982;width:25%;float:right;font-size:12px;height: 26px;line-height: 24px;border: 1px solid #268F6E;border-radius: 13px;background:#fff" :class="{ getdisable: getdisable }" @click="getCode" id="v_code">{{btnValue}}</div>
        </div>
      </div>
      <div class="btn" @click="checkMessage">下一步</div>
    </div>
  </div>
</template>
<script lang="ts">
import '../../style/reservaIndex_index.css';
import 'vant/lib/toast/style';
import 'vant/lib/dialog/style';
import { Toast,Dialog } from 'vant';
import { Component, Vue, Prop } from 'vue-property-decorator';
import { cloudApi } from '@/api/indexApi';
import { Alert } from '@/utils';
import Header from '@/components/Header.vue';
import router from '@/router';
Vue.use(Dialog);
Component.registerHooks(['beforeRouteUpdate', 'beforeRouteLeave', 'beforeRouteLeave']);
@Component({
  components: { Header },
})
export default class MainPage extends Vue {
  phoneNumber = ''
  checkCode = ''
  checkInfoPhone = ''
  // address = 'https://wechattest.chinalife-p.com.cn/wechatpageview/Claimlistwx_index.html?appid=wxb1b70bf91a06f3e5&code=061m65Ga1OaPnA0w7AFa1uahTn0m65GD&state=ea70f6e5ccc29530148a5dcadb578670a988d18dd169e093bcc63c563b31d9caopenidoWcBG44J-8SeTxYHyH4NDyqPyTos'
  // app_id: string = this.address.split("?")[1].split("&")[0].split("=")[1];
  // code: string = this.address.split("&")[1].split("=")[1];
  openId: any = '';
  unionId:any='';
  route:any='';
  // unionId: string = 'ea70f6e5ccc29530148a5dcadb578670a988d18dd169e093bcc63c563b31d9ca';
  // uid:string = this.address.split("&")[2].split("=")[1];
  validateCodeType = "0"
  checkInfo_type = "0"
  getdisable = false
  btnValue = '获取验证码'
  myCardList:any = []
  jumpflag = 0
  user_card_type= ''
  userId = ''
  user_phone = ''
  appid= ''
  code= ''
  source=''//页面来源
  sourceBack=''//返回几步
  created() {
      if(this.$route.query.route){//别的vue页面跳转来的
        this.route = this.$route.query.route
        this.openId = this.$route.query.openId
        this.unionId = this.$route.query.unionId
        if(!this.openId&&!this.unionId){//无openId  unionId 跳授权
          //生产
          // let url='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5668b394c2053c79&redirect_uri=https%3a%2f%2fwechat.chinalife-p.com.cn%2fwechatpageview%2fdist/index.html%3fappid%3dwx5668b394c2053c79&response_type=code&scope=snsapi_base&state=state_checkPhoneInfo#wechat_redirect'
          //测试
          let url='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb1b70bf91a06f3e5&redirect_uri=https%3a%2f%2fwechattest.chinalife-p.com.cn%2fwechatpageview%2fdist/index.html%3fappid%3dwxb1b70bf91a06f3e5&response_type=code&scope=snsapi_base&state=state_checkPhoneInfo#wechat_redirect'
          sessionStorage.setItem('route',this.route)
          window.location.href=url  
        }
      }else{//授权回来的链接
        var address = location.href;
        this.appid = address.split("appid=")[1].split("&code")[0];
        this.code = address.split("code=")[1].split("&state")[0]
        this.source=address.split("checkPhoneInfoopenid")[1]
        this.route = sessionStorage.getItem('route')
        sessionStorage.setItem('sourceBack','xiaochengxu')
        // console.log('zwh',this.source)
        // if(this.source){//小程序来源
        //  let sourceUrl='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb1b70bf91a06f3e5&redirect_uri=https%3a%2f%2fwechattest.chinalife-p.com.cn%2fwechatpageview%2fwarranty_index.html%3fappid%3dwxb1b70bf91a06f3e5&response_type=code&aaa=aa&scope=snsapi_base&state=82d5fa5048fae3251c0e5beadf2a6e7616c20c62cebde8e7a3a91453a1f9f69aopenidoWcBG4_5kZ0fv4IGtgDUToTPLsmU#wechat_redirect'
        //  sessionStorage.setItem('route', '')
        //  sessionStorage.setItem('sourceUrl', sourceUrl)
        // }
        // if(sessionStorage.getItem('route')){//vue页面来源
        //   this.route = sessionStorage.getItem('route')
        //   sessionStorage.setItem('sourceUrl', '')

        // }
        this.getUnionIdAndOpenId()
      }
  }
  //  mounted() {
  //     if (window.history && window.history.pushState) {
  //       // 向历史记录中插入了当前页
  //       history.pushState(null, null, document.URL);
  //       window.addEventListener('popstate', this.goBack, false);
  //    }    
  //  }
  //   destroyed () {
  //     window.removeEventListener('popstate', this.goBack, false);
  //   }
  // goBack () {
  //   //指定返回路径
  //    if(sessionStorage.getItem('sourceBack')=='xiaochengxu'){
  //       sessionStorage.removeItem('sourceBack')
  //        if((window as any).wx.miniProgram){
  //         (window as any).wx.miniProgram.navigateBack({
  //           delta: history.length
  //         })
  //       }
  //     }
  // }
  //获取unionId
  // getUnionId(){
  //   cloudApi.getThreeidById({id:this.uid}).then(res => {
  //     this.unionId = res.data.unionId
  //     console.log(res)
  //   })
  // }
  // myInformation_getbind(){
  //   const data = {
  //       openid: this.openId,
  //       unionid: ""
  //   }
  //   let _this= this
  //   cloudApi.getMyBussinessCardURL(data).then(res => {
  //     if(res.status = 200){
  //       if(res.data.result.length !== 0){
  //         let userData:any={"openId":_this.openId,"unionId":_this.unionId}
  //         sessionStorage.setItem("userData",JSON.stringify(userData))
  //         if(_this.route){//别的页面进来
  //         }else{
  //           _this.$router.push("personalCard")
  //         } 
  //       }
  //     }
  //   })
  // }
  getUnionIdAndOpenId(){
    var _this = this;
    cloudApi.getUnionIdAndOpenId({appid: _this.appid, code: _this.code}).then(function(res: any) {
        if (res.data) {
          if(res.data.openId){
            _this.unionId = res.data.unionId;
            _this.openId = res.data.openId;
          }else{
             Dialog.alert({ title: '温馨提示', message: "未获取到openId" })
          }
        }else{
           Dialog.alert({ title: '温馨提示', message: "系统异常！" })
        }
      });
  }
  //获取验证码
  getCode(){
    // 手机号为空
    if (this.phoneNumber === '') {
      Toast('请输入手机号');
      return;
    } else if (!/^1[3456789]\d{9}$/.test(this.phoneNumber)) {
      // 检测手机号格式
      Toast('请输入正确的手机号');
      return;
    }
    cloudApi.getValidateCode({phoneNumber:  window.btoa(this.phoneNumber)}).then(res => {
      if(res.status == 200){
        if (res.data.requestTime == "1") {
          Dialog.alert({ title: '温馨提示', message: "尊敬的客户，您获取验证码的频率过高，请稍后获取！" })
          return;
        }
        this.checkInfo_type = "0"; //电商可以验证码
        if (res.data.getValidateCode1.respCode == "01") {
          Dialog.alert({ title: '温馨提示', message: "手机验证码已经发出！" })
            this.validateCodeType = "01"; //注册调用成功
            this.verifiction_code2(); //客户验证
        } else if (res.data.getValidateCode1.respCode == "10") {
            //电商获取不到验证码
            this.checkInfo_type = "1"; //电商获取不到验证码
            this.information_checkInfo();
        } else {
            if (res.data.getValidateCode2.respCode == "01") {
              Dialog.alert({ title: '温馨提示', message: "手机验证码已经发出！" })
                this.validateCodeType = "02"; //登录调用成功
                this.verifiction_code2(); //客户验证
            } else {
                if (res.data.getValidateCode1.respCode == "10" || res.data.getValidateCode1.respCode == "49" ||
                    res.data.getValidateCode2.respCode == "10" || res.data.getValidateCode2.respCode == "49") {
                    //电商获取不到验证码
                    this.checkInfo_type = "1"; //电商获取不到验证码
                    this.information_checkInfo();
                } else {
                  Dialog.alert({ title: '温馨提示', message: "发送验证码失败，请稍后再次获取！" })
                }
            }
          }
       }
    })
  }
  //倒计时
  verifiction_code2(){
    var count = 60;
    const _this = this
    _this.getdisable = false;
    var time = setInterval(function () {
        _this.getdisable = true;
        count--;
        _this.btnValue = count + "秒后获取";
        if (count == -1) {
            clearInterval(time);
            _this.btnValue = "重新获取";
            _this.getdisable = false;
        }
    }, 1000)
  }
  information_checkInfo(){
    //  Toast.loading({
    //   duration: 0,
    //   message: '加载中...',
    //   forbidClick: true,
    // });
    const data = {
      open_id: this.openId,
      mobile_Phone: window.btoa(this.phoneNumber) //手机号
    }
    cloudApi.getCheckCodeOneURL(data).then(res=> {
      // Toast.clear();
      if(res.status == 200){
        if (res.data.result == "1") {
          Dialog.alert({ title: '温馨提示', message: "手机验证码已经发出！" })
          this.checkInfoPhone = this.phoneNumber;
          this.verifiction_code2(); //客户验证
        } else if (res.data.result == "2") {
          Dialog.alert({ title: '温馨提示', message: "尊敬的用户，您获取验证码的频率过高，请稍后再次获取!" })
        } else {
          Dialog.alert({ title: '温馨提示', message: "发送手机验证码失败，请重新获取！" })
        }
      }else{
        Dialog.alert({ title: '温馨提示', message: "暂时不能为您服务，请拨打95519或4008695519" })
      }
    })
  }
  checkMessage(){//点击下一步按钮
    if(this.checkInfo_type!== "0"){//电商验证
      const data = {
        open_id: this.openId,
        verifyCode: this.checkCode //验证码
      }
      cloudApi.checkMessageAuthen(data).then(res =>{
        if(res.status == 200){
          if(res.data.result == "1"){
            this.getUserInfo()
          } else if (res.data.result == "2") {
            Dialog.alert({ title: '温馨提示', message: "短信验证码已失效，请重新获取！" })
            return;
          } else {
            Dialog.alert({ title: '温馨提示', message: "短信验证码不正确，请重新填写！" })
            return;
          }
        }
      })
    }else {
      const data1 = {
        phoneNumber: btoa(this.phoneNumber),
        validateCode: this.checkCode,
        validateCodeType: this.validateCodeType
      }
      cloudApi.checkValidateCode(data1).then(res => {
        var data = JSON.parse(decodeURIComponent(atob(res.data.result)));
        console.log(data)
          if(data.checkValidateCode1.respCode == "01"){
            this.getUserInfo()
          }else{
            Dialog.alert({ title: '温馨提示', message: data.checkValidateCode1.errorMsg })
          }
      })
    }
  }
  //通过手机号查询是否绑定是三要素
  getUserInfo(){
    const data = {
      phone: this.phoneNumber,
      openid: this.openId,
      datasource: 'zgs'
    }
    cloudApi.userByPhone(data).then(res => {
      var data1 = res.data.result;
      if (data1 == '' || data1 == "" || data1 == undefined || data1 == "''") {
          this.jumpflag = 0;
          //获取userid
          this.information_bindding();
      } else {
          this.myCardList = [];
          this.myCardList.push(data1)
          this.myCardList[0]["relation1"] = "本人"; //与本人关系
          this.jumpflag = 1;
          console.log("myCardList",this.myCardList)
          this.information_bindding()
      }
    })
  }
  //保存接口
  information_bindding(){
    const data = {
      openid: this.openId,
      user_phone: this.phoneNumber,
      verifyCode: this.checkCode,
      type: this.validateCodeType
    } 
    let _this =this   
    cloudApi.queryUserInfoByPhone(data).then(res => {
      var data = JSON.parse(decodeURIComponent(atob(res.data.result)));
      console.log(data)
        //alert("获取三要素信息" + JSON.stringify(data));
        if (data.result == "error") {
          Dialog.alert({ title: '温馨提示', message: data.inf })
        } else {
            _this.user_card_type = data.result.user_card_type; //证件类型
            _this.userId = data.result.id; //获取到userid，id中存放userID的值      
            _this.user_phone = data.result.user_phone; //手机号
            let userData:any={
              "openId":_this.openId,
              "mobile":_this.user_phone,
              "userId":_this.userId,
              "unionId":_this.unionId
            }
            sessionStorage.setItem("userData",JSON.stringify(userData))   
            if (_this.jumpflag == 0) {
                if(_this.route){//别的页面进来需要返回原来页面
                  _this.$router.push({path: 'idCardInfo',query: {route:_this.route}});
                }else{
                  _this.$router.push('idCardInfo');
                } 
            } else if (_this.jumpflag == 1) {
               if(_this.route){//别的页面进来需要返回原来页面
                  let route:any = JSON.parse(_this.route)
                  _this.$router.push(route)
                }else if(sessionStorage.getItem('sourceUrl')){//小程序来源
                  window.location.href=sessionStorage.getItem('sourceUrl') 
                }else{
                _this.$router.push("personalCard")
              } 
            }
        }
    })
  }

}
</script>
<style lang="less" scoped>
.phoneInfo{
  background: url("../../assets/images/myInfo/info_center.png") no-repeat;
  background-size:100% 100%;
  position:absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  text-align: center;
}
.midContent{
  width: 90%;
  height: 300px;
  background: #FFFFFF;
  box-shadow: 0px 15px 15px 0px rgba(4, 0, 0, 0.05);
  border-radius: 40px;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  padding: 20px;
}
.btn{
  width: 100%;
  height: 36px;
  line-height: 36px;
  background: #00A08A;
  border-radius: 18px;
  color:#fff;
  font-size: 16px;
}
</style>

